/*
 Fading
 
 This example shows how to fade an LED using the analogWrite() function.
 
 The circuit:
 * LED attached from digital pin 9 to ground.
 
 Created 1 Nov 2008
 By David A. Mellis
 Modified 17 June 2009
 By Tom Igoe
 
 http://arduino.cc/en/Tutorial/Fading
 
 */

int sensorPin = 0;
int ledPin = 9;    // LED connected to digital pin 9
long previousTick = 0;
long currentTick = 0;
long interval = 2;
int brightness = 0;
boolean fadeIn = true;
int sensorValue = 0;
int baseBrightness = 10;

void setup()  { 
  // nothing happens in setup 
} 

void loop()  { 
  currentTick = millis();  
  if (currentTick - previousTick > interval) {
    previousTick = currentTick;
    fireEvent();
  }
}

void fireEvent() {
  readBrightness();
  analogWrite(ledPin, brightness);
  brightness -= 1;
  if (brightness < 0) {
    brightness = 0;
  }
}

void readBrightness() {
  sensorValue = analogRead(sensorPin);
  int newBrightness = (sensorValue * 100);
  if (newBrightness > brightness) {
    if (newBrightness > 255) {
      newBrightness = 255;
    }
    brightness = newBrightness;
  }
}


